package com.intellagric.service.search.dao.agriecom_product;

import com.intellagric.common.pojo.LayuiDataGridResult;
import com.intellagric.pojo.AgriecomProduce;
import com.intellagric.service.search.agriecom.pojo.AgriecomProductResult;
import com.intellagric.service.search.mapper.AgriecomProductSearchMapper;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServer;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrDocument;
import org.apache.solr.common.SolrDocumentList;
import org.apache.solr.common.SolrInputDocument;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Repository
public class AgriecomProductSearchDao {
    @Autowired
    private AgriecomProductSearchMapper productSearchMapper;

    @Autowired
    @Qualifier("SolrServer2")
    private SolrServer solrServer;

    /**
     * 导入全部数据到索引库
     * @return
     */
    public LayuiDataGridResult addALL(){
        List<AgriecomProductResult> resultList=productSearchMapper.getList();
        System.out.println("add ALL");
        for (AgriecomProductResult product:resultList){
            SolrInputDocument document=new SolrInputDocument();
            document.setField("id",product.getProduceId());
            document.setField("produce_name",product.getProduceName());
            document.setField("stock",product.getStock());
            document.setField("price",product.getPrice()+"");
            document.setField("unit",product.getUnit());
            document.setField("merchant_id",product.getMerchantId());
            document.setField("merchant_name",product.getMerchantName());
            document.setField("produce_img",product.getProduceImg());
            document.setField("category_id",product.getCategoryId());
            document.setField("category_name",product.getCategoryName());

            document.setField("producing_area",product.getProducingArea()+"");//防止取出时空指针异常
            document.setField("produce_brief",product.getProduceBrief()+"");
            document.setField("produce_parameter",product.getProduceParameter()+"");
            document.setField("remarks",product.getRemarks()+"");
            try {
                solrServer.add(document);
            } catch (Exception e) {
                e.printStackTrace();
                return LayuiDataGridResult.fail();
            }
        }
        try {
            solrServer.commit();
        } catch (Exception e) {
            e.printStackTrace();
            return LayuiDataGridResult.fail();
        }
        return LayuiDataGridResult.success();
    }


    public LayuiDataGridResult keywordQuery(SolrQuery query) throws SolrServerException {
        QueryResponse queryResponse = solrServer.query(query);
        SolrDocumentList documents = queryResponse.getResults();

        Map<String, Map<String, List<String>>> highlighting = queryResponse.getHighlighting();
        long total=documents.getNumFound();
        List<AgriecomProductResult> resultList=new ArrayList<>();
        for (SolrDocument document:documents){
            AgriecomProductResult result=new AgriecomProductResult();
            result.setProduceId((String) document.getFieldValue("id"));
            result.setCategoryId((String)document.getFieldValue("category_id"));
            result.setCategoryName((String)document.getFieldValue("category_name"));
            result.setMerchantId((String)document.getFieldValue("merchant_id"));
            result.setMerchantName((String)document.getFieldValue("merchant_name"));
            result.setStock((Integer) document.getFieldValue("stock"));
            result.setUnit((String)document.getFieldValue("unit"));
            result.setPrice(Float.toString((Float)document.getFieldValue("price")));//solr中price配置为float类型
            result.setProduceBrief((String) document.get("produce_brief"));
            result.setRemarks((String)document.get("remarks"));
            //生产地
            Object area=document.getFieldValue("producing_area");
            if(area!=null&&!area.equals(""))
                result.setProducingArea((String)area);
            else
                result.setProducingArea("");

            //取第一张图片
            String imgs=(String)document.getFieldValue("produce_img");

            if(imgs!=null&&!imgs.equals(""))
                result.setProduceImg(imgs.split(",")[0]);
            //高亮获取
            String produceName="";
            if (highlighting!=null)
                produceName=(String)highlighting.get(result.getProduceId()).get("produce_name").get(0);
            else
                produceName=(String) document.get("produce_name");
            result.setProduceName(produceName);
            resultList.add(result);
        }

        if(resultList.size()==documents.size())
            return LayuiDataGridResult.success().add(resultList,total);
        return LayuiDataGridResult.fail();
    }

    public LayuiDataGridResult paramQuery(SolrQuery query){
        try {
            QueryResponse response = solrServer.query(query);
            SolrDocumentList documents=response.getResults();
            long counts=documents.getNumFound();
            List<AgriecomProductResult> results=new ArrayList<>();
            for (SolrDocument document:documents){
                AgriecomProductResult result=new AgriecomProductResult();
                result.setProduceId((String) document.getFieldValue("id"));
                result.setProduceName((String)document.getFieldValue("produce_name"));
                result.setCategoryId((String)document.getFieldValue("category_id"));
                result.setCategoryName((String)document.getFieldValue("category_name"));
                result.setMerchantId((String)document.getFieldValue("merchant_id"));
                result.setMerchantName((String)document.getFieldValue("merchant_name"));
                result.setStock((Integer) document.getFieldValue("stock"));
                result.setUnit((String)document.getFieldValue("unit"));
                result.setPrice(Float.toString((Float)document.getFieldValue("price")));//solr中price配置为float类型
                result.setProducingArea((String) document.getFieldValue("producing_area"));
                result.setProduceBrief((String) document.get("produce_brief"));
                result.setRemarks((String)document.get("remarks"));
                if(document.getFieldValue("produce_img")!=null)
                    result.setProduceImg(((String)document.getFieldValue("produce_img")).split(",")[0]);//取第一张放入
                result.setProduceParameter((String)document.getFieldValue("produce_parameter"));
                results.add(result);
            }
            return LayuiDataGridResult.success().add(results,counts);
        } catch (SolrServerException e) {
            e.printStackTrace();
        }
        return LayuiDataGridResult.fail();
    }
    //获取总记录数
    public long getCount(String categoryId) {
        SolrQuery query=new SolrQuery();
        query.set("q","*:*");
        query.setFilterQueries("category_id:" + categoryId);
        query.setRows(Integer.MAX_VALUE);
        try {
            return solrServer.query(query).getResults().getNumFound();
        } catch (SolrServerException e) {
            e.printStackTrace();
        }
        return 0;
    }
}
